<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function sum(arr) {
      arr.unshift(0)
      arr.push(0)
      const mod = 10 ** 9 + 7, n = arr.length, stack = []
      let res = 0
      for (let i = 0; i < n; i++) {
        while (arr[i] < arr[stack[stack.length - 1]]) {
          const idx = stack.pop()
          const l = idx - stack[stack.length - 1], r = i - idx
          res = (res + arr[idx] * l * r) % mod
        }
        stack.push(i)
      }
      return res
    };
    console.log(sum([3, 1, 2, 4]));
  </script>
</body>

</html>